/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jee.forum.beans;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import jee.forum.controller.SessionController;
import org.apache.log4j.Logger;

/**
 *
 * @author Tobi
 */
@ManagedBean(name = "Session")
@SessionScoped
public class Session implements Serializable {

    @EJB
    private SessionController sessionCtr;

    Logger log = Logger.getLogger(Session.class);

    //User specific Informations
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isLogin() {
        if (sessionCtr.getSession() != null) {
            return false;
        }
        return true;

    }


     public String login() {
        log.info(username + password);
        
        try {
            boolean userExists = sessionCtr.login(username, password);

            if (!userExists) {
                return "index";
            }

            //.getSession(boolean), true if we want to create a new one
            FacesContext context = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
            sessionCtr.setSession(session);

            return "index";

        } catch (Exception e) {
            log.error("Error on login, username or password maybe not correct");
            return "index";
        }
    }

    public String logout(){
        if(sessionCtr.getSession() != null){
            sessionCtr.getSession().invalidate();
        }
        return "index";
    }



}
